package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

@Slf4j
@Service
public class VodServiceImpl implements VodService {

    @Autowired
    private VodConstantProperties vodConstantProperties;


    @Override
    @NotNull
    public HashMap<String, Object> getVodMediaMap(MultipartFile file) {
        String fileId="";
        String mediaUrl="";

        //初始化上传客户端
        VodUploadClient client = new VodUploadClient(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());

        //构建上转请求
        VodUploadRequest request = new VodUploadRequest();
        String tempPath = UploadFileUtil.uploadTempPath("D:\\picture\\", file);
        request.setMediaFilePath(tempPath);
        request.setConcurrentUploadNumber(5);// 对大文件起作用。（s3：minio:大文件上传（断点续传 秒传  分片上传 ））

        //调用上传方法
        try {
            VodUploadResponse response = client.upload("ap-guangzhou", request);
            fileId = response.getFileId();
            mediaUrl = response.getMediaUrl();
            log.info("Upload FileId = {}", response.getFileId());
        } catch (Exception e) {
            // 业务方进行异常处理
            log.error("Upload Err", e);
        }
        //4.构建上传文件在vod上的文件标识的地址
        HashMap<String, Object> map = new HashMap<>();
        map.put("mediaFileId",fileId);
        map.put("mediaUrl",mediaUrl);
        return map;
    }

    @Override
    public TrackMediaInfoVo getMediaInfo(String mediaFileId) {
        try {
            // 1、实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            // 2、实例化vod的client对象
            VodClient client = new VodClient(cred, vodConstantProperties.getRegion());
            // 3、实例化一个请求对象
            DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
            // 3.1 给请求对象设置参数
            String[] fileIds1 = {mediaFileId};
            req.setFileIds(fileIds1);
            // 4、得到vod的响应
            DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);
            // 输出json格式的字符串回包
            System.out.println(AbstractModel.toJsonString(resp));
            TrackMediaInfoVo trackMediaInfoVo = new TrackMediaInfoVo();
            MediaInfo[] mediaInfoSet = resp.getMediaInfoSet();

            if (mediaInfoSet != null && mediaInfoSet.length > 0) {
                MediaInfo mediaInfo = mediaInfoSet[0];
                MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
                MediaMetaData metaData = mediaInfo.getMetaData();
                Float audioDuration = metaData.getAudioDuration();
                trackMediaInfoVo.setSize(metaData.getSize());
                trackMediaInfoVo.setDuration(audioDuration);
                trackMediaInfoVo.setMediaUrl(basicInfo.getMediaUrl());
                trackMediaInfoVo.setType(basicInfo.getType());
            }

            return trackMediaInfoVo;

        } catch (TencentCloudSDKException e) {
            log.error("获取媒体信息失败：{}", e.getMessage()); // 异常吃掉了

//            throw new GuiguException(201,"获取媒体信息失败");
        }
        return null;
    }

    @Override
    public void removeVodInfo(String mediaFileId) {
        try{
            if (mediaFileId==null){
                log.error("该声音没有媒体信息");
                throw new GuiguException(201,"该声音没有媒体信息");
            }
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            // 实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred,  vodConstantProperties.getRegion());
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileId);
            // 返回的resp是一个DeleteMediaResponse的实例，与请求对象对应
            DeleteMediaResponse resp = client.DeleteMedia(req);
            // 输出json格式的字符串回包
            System.out.println(AbstractModel.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.error("删除媒体信息失败：{}", e.getMessage());
            throw new GuiguException(201,"删除媒体信息失败");
        }
    }

}
